﻿/* ----------------------------------------------------------------------------
 * Copyright (c) Philip Stears 
 *
 * This source code is subject to terms and conditions of the Microsoft Public 
 * License (Ms-PL).
 * 
 * By using this source code in any fashion, you are agreeing to be bound 
 * by the terms of the Microsoft Public License.
 * 
 * To request a copy of the Microsoft Public License, send a request by email
 * to license@connectbasic.net.
 *
 * This notice must not be removed from this software.
 * ---------------------------------------------------------------------------- */

namespace ConnectBasic.ObjectModel
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using ConnectBasic.Execution;
    using DlrExpression = Microsoft.Linq.Expressions.Expression;

    /// <summary>
    /// Represents a block of statements.
    /// </summary>
    public class Block : NodeBase
    {
        private ReadOnlyCollection<StatementNodeBase> mStatements;

        /// <summary>
        /// Initializes a new instance of the <see cref="Block" /> class.
        /// </summary>
        /// <param name="statements">The statements which define the block.</param>
        public Block(IEnumerable<StatementNodeBase> statements)
        {
            if (statements == null) throw new ArgumentOutOfRangeException("statements");
            mStatements = new ReadOnlyCollection<StatementNodeBase>(statements as IList<StatementNodeBase> ?? new List<StatementNodeBase>(statements));
        }

        /// <summary>
        /// Gets the statements which define the block.
        /// </summary>
        public IEnumerable<StatementNodeBase> Statements
        {
            get { return mStatements; }
        }

        /// <inheritdoc />
        public override DlrExpression Compile(BasicCodeGenerator gen)
        {
            if (mStatements.Count == 0)
            {
                return DlrExpression.Empty();
            } 
            else 
            {
                var statements = new DlrExpression[mStatements.Count];

                for (int i = 0; i < statements.Length; i++)
                {
                    statements[i] = mStatements[i].Compile(gen);
                }

                return DlrExpression.Block(statements);
            }
        }
    }
}
